<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once('Entity/Doc_Tags_Entity.php');        
class Doc_Tags_Model extends Doc_Tags_Entity
{  
    public function __construct()
    {
        parent::__construct();
    }
    
    public function addnewtags($arrTags)
    {
        $this->load->model('Doc_Tags_Doc_Model');
        foreach ($arrTags as $tag) {
            $this->setTags($tag);
            $this->save();
        }
    }
    
    public function getTagbyDoc($docId)
    {
        $sql = "SELECT t.id, t.tags
            FROM doc_documents d
            INNER JOIN doc_tags_doc td ON td.doc_id = d.id
            INNER JOIN doc_tags t ON t.id = td.tag_id
            WHERE d.id = ?";
        $query = $this->db->query($sql, array($docId));
        return $query->result();
    }
    
    public function tagsRemoved($str)
    {
        $sql = "SELECT t.id
        	FROM doc_documents d
        	INNER JOIN doc_tags_doc td ON td.doc_id = d.id
        	INNER JOIN doc_tags t ON t.id = td.tag_id
        	WHERE d.id = 2 AND t.tags NOT IN ($str) ";
        $query = $this->db->query($sql);
        $obj = $query->result();
        foreach ($obj as $row) {
            $this->db->delete('doc_tags_doc', array('tag_id' => $row->id));
        }
        return $obj;    
    }
    
    public function tagsIdList($arrTags)
    {
        $arr = array();
        foreach ($arrTags as $tag) {
            $arr[] = "'".$tag."'";
        }
        $str = implode(',', $arr);
       
        $sql = "SELECT t.id 
            FROM doc_tags t
            WHERE t.tags IN ($str) ";
        $query = $this->db->query($sql);
        $obj = $query->result();
        $arr = array();    
        foreach ($obj as $ob) {
            $arr[] = $ob->id;
        }        
        return $arr; 
    }
}